#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2025/6/17 21:37
# @Author  : wuyupeng
# @FileName: qemu-upload.py
# @Software: PyCharm
import os
import sys
import click
import base64
import logging
from pathlib import Path

from repo_uploaders.repo_manager import RepoManagerFactory
from repo_uploaders.impls.obs_apt_repo_manager import OBSPipeLineLogHelper

OBS_AK = os.getenv("ak")
OBS_SK = os.getenv("sk")
OBS_ENDPOINT = os.getenv("obs_endpoint")
PUBLIC_KEY = os.getenv("public_key")
PRIVATE_KEY = os.getenv("private_key")
APT_BUCKET = os.getenv("apt_bucket_name")
OBS_ROOT = os.getenv("obs_root")
GPG_PASSPHRASE = os.getenv("passphrase")
DEBUG_INFO = os.getenv("DEBUG") == "True"

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s")


@click.command()
@click.option("--deb_path")
@click.option("--codename")
@click.option("--component")
@click.option("--arch")
def main(deb_path, codename, component, arch):
    params = [OBS_AK, OBS_SK, OBS_ENDPOINT, APT_BUCKET, deb_path, codename, component, arch, PUBLIC_KEY, PRIVATE_KEY]

    if DEBUG_INFO:
        logging.info(">>>>")
        logging.info(params)
        logging.info("<<<<")

    if not all(params):
        logging.info(f"Lack of params{params}, Please check.")
        sys.exit(-1)

    obs_helper = OBSPipeLineLogHelper(OBS_AK, OBS_SK, OBS_ENDPOINT, APT_BUCKET)
    deb_full_path = Path(".").resolve() / f"qemu_{arch}.deb"
    deb_full_path.parent.mkdir(parents=True, exist_ok=True)
    pkgs_resp = obs_helper.get_file(deb_path, str(deb_full_path))
    if DEBUG_INFO:
        logging.info(">>>>")
        logging.info(f"pkgs_resp: {pkgs_resp.status}, {pkgs_resp.errorMessage}, {pkgs_resp.reason}, {pkgs_resp.indicator}, {pkgs_resp.resource}")
        logging.info("<<<<")
    if pkgs_resp.status >= 300:
        raise FileNotFoundError(f"获取 qemu 失败！{pkgs_resp.errorMessage}")

    if DEBUG_INFO:
        logging.info(f"deb: {deb_full_path}")

    decoded_private_key = base64.b64decode(PRIVATE_KEY).decode()
    apt_mgr = RepoManagerFactory.create("obs", deb_full_path, codename, component, arch, OBS_ROOT, is_debug=DEBUG_INFO)
    apt_mgr.init_apt_helper(OBS_AK, OBS_SK, OBS_ENDPOINT, APT_BUCKET)
    apt_pkg = apt_mgr.prepare_package(decoded_private_key, GPG_PASSPHRASE)
    apt_mgr.upload_package(apt_pkg, PUBLIC_KEY)


if __name__ == '__main__':
    main()
